package com.easepal7506a.project.ui.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.easepal.socketiolib.WebSocketClient;
import com.easepal.socketiolib.callback.ActionListener;
import com.easepal.socketiolib.callback.EventsListener;
import com.easepal.socketiolib.model.SocketModel;
import com.easepal7506a.project.Constant.CommmandNum;
import com.ogawa.base.Constant.Constants;
import com.easepal7506a.project.R;
import com.easepal7506a.project.interfaces.OnAutoFinish;
import com.easepal7506a.project.manager.DataManager;
import com.easepal7506a.project.network.CommondManager;

import com.easepal7506a.project.observer.SocketDataObserver;
import com.easepal7506a.project.observer.SoftApSucceedObserver;
import com.easepal7506a.project.ui.activity.activity_7506l.ProMasDetailActivity7506L;
import com.easepal7506a.project.ui.iview.IHomeView7506;
import com.easepal7506a.project.ui.presenter.HomePresenter7506;
import com.easepal7506a.project.utils.ActivityUtils;
import com.example.reslib.utils.PreferenceWrapper;
import com.example.reslib.utils.ToastUtils;
import com.ogawa.base.callback.GetUpdataCallback;
import com.ogawa.base.callback.NormalCallback;
import com.ogawa.base.network.BaseResponse;
import com.ogawa.base.network.bean.BeanUpdata;
import com.ogawa.base.utils.CommonUtil;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import cn.ljuns.logcollector.LogCollector;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;


/**
 * 首页
 */
public class HomeActivity7506 extends BaseActivity implements View.OnClickListener, IHomeView7506, EventsListener, SoftApSucceedObserver.onSoftApLis {
    private boolean isExit;
    private HomePresenter7506 mPresenter;
    private MyHandler myHandler = new MyHandler(this);
    private LinearLayout mLlAuto;
    private LinearLayout mLlHand;
    private LinearLayout mLlAtti;
    private boolean isFirst = true;
    private TextView mTvNoNet;
    private ImageView mIvWifi;
    private RelativeLayout mRlRunning;
    private TextView mTvRunning;

    private IntentFilter intentFilter;
    private Disposable mDisposable;
    private int mCount = 0;
    private NetworkChangeReceiver networkChangeReceiver;
    private int mRunning = 0;//1 专业按摩  2 高级按摩
    private String mAutoName;
    private PreferenceWrapper mSp;
    private String mSaveVersion = "";
    private int mSaveCount = 0;
    private int repeatCount;
    private boolean is7506L;
    private  boolean  hasFristConnect;//是否首次连接成功websocket过


    @Override
    public void initTitleBar() {
        super.initTitleBar();
        titleBar.setTitleNameGone();
        titleBar.setBackGone();
        titleBar.showWifi();
    }

    @Override
    public void initView(int layoutId) {
        super.initView(layoutId);
        is7506L=getIntent().getBooleanExtra("is7506L",false);
        DataManager.getInst().setIs7506L(is7506L);
        mSp = new PreferenceWrapper();
        mSaveVersion = mSp.getStringValue(Constants.SAVE_VERSION, "");
        mSaveCount = mSp.getIntValue(Constants.SAVE_COUNT, 0);
        String mSn = mSp.getStringValue(Constants.SN, "");
        DataManager.getInst().setmSn(mSn);
        mLlAuto = findViewById(R.id.linear_attitude_adjustment);
        mLlHand = findViewById(R.id.linear_high_massage);
        mLlAtti = findViewById(R.id.linear_professional_massage_7506);
        mTvNoNet = findViewById(R.id.home_tv_nonet);
        mIvWifi = findViewById(R.id.title_wifi);
        mRlRunning = findViewById(R.id.home_rl_running);
        mTvRunning = findViewById(R.id.home_tv_running);
        mLlAtti.setOnClickListener(this);
        mLlHand.setOnClickListener(this);
        mLlAuto.setOnClickListener(this);
        mIvWifi.setOnClickListener(this);
        mRlRunning.setOnClickListener(this);
        mPresenter = new HomePresenter7506(this);
////输出log
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }
        LogCollector.getInstance(getApplication())
                .setCleanCache(true)
//                .setTag("SendCommond7506","socket7506","TEST")

                .setTag("TEST")
                .setCacheFile(DataManager.getInst().creatFile())
                .setCleanCache(true)
                .start();
// //输出log结束
        //网络状态
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver, intentFilter);


        WebSocketClient.getInstance(getApplication()).registerListener(this);
        WebSocketClient.getInstance(getApplication()).setBaseUrl(com.example.reslib.Constants.SOCKET_ADDRESS);
        SoftApSucceedObserver.getInst().registerObserver(this);

    }

    private void connectSocket(String token) {

        WebSocketClient.getInstance(getApplication()).connect(token, new ActionListener() {
            @Override
            public void onSuccess() {
                hasFristConnect = true;
                DataManager.getInst().setConnectSocket(true);

                Log.e("SockeStatus", "succeeddddd");
            }

            @Override
            public void onFailure(String error) {
                Log.e("SockeStatus", "onFailure==" + error);
                DataManager.getInst().setConnectSocket(false);
            }
        });

    }


    @Override
    public void loadData() {
        super.loadData();
        if (TextUtils.isEmpty(DataManager.getInst().getmSn())) {
//            getPer();
            ToastUtils.showShortToast(this, "请先配置网络");
        } else {
            showkProgress("初始化中，请稍等...");
            mPresenter.getOnline(this, DataManager.getInst().getmSn());

        }


    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_main_7506;
    }

    @Override
    protected void onStart() {
        super.onStart();


    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.linear_attitude_adjustment) {

            if (DataManager.getInst().isOpen()) {
                ActivityUtils.startAttitudeAdjustmentActivity(this);
            } else {
                ToastUtils.showShortToast(this, "请先开机");
            }


        } else if (i == R.id.linear_professional_massage_7506) {//专业按摩
            if (DataManager.getInst().isOpen()) {
                if(is7506L){
                    ActivityUtils.startProfessionMassaActivityL(this);
                }
                else {
                    ActivityUtils.startProfessionMassaActivity(this);
                }

            } else {

                ToastUtils.showShortToast(this, "请先开机");
            }


        } else if (i == R.id.linear_high_massage) {//高级按摩
            if (DataManager.getInst().isOpen()) {
//                自动程序是否在运行
                if (!DataManager.getInst().getValue(CommmandNum.mStatusAuto).equals("0")) {
                    showNoticeDialog(new OnAutoFinish() {
                        @Override
                        public void onAutoClose() {
                            stopAuto();
                        }
                    });
                } else {
                    ActivityUtils.startAdvancedMassageActivity(HomeActivity7506.this);
                }

            } else {
                ToastUtils.showShortToast(this, "请先开机");
            }


        } else if (i == R.id.title_wifi) {
            if(CommonUtil.isOPenGPS(this)){
                getPer();
            }
            else {
                ToastUtils.showShortToast(this,"配网需要使用定位权限，请先开启定位服务");
            }

        } else if (i == R.id.home_rl_running) {
            if (DataManager.getInst().isPause()) {
                sendCommond(CommmandNum.PAUSE);
            }
            Log.e("mRUNNING",mRunning+"====");
            if (mRunning == 1) {
                if(is7506L){
                    ActivityUtils.startProMasDetailActivityL(this, mAutoName);
                }
                else {
                    ActivityUtils.startProMasDetailActivity(this, mAutoName);
                }


            } else {
                ActivityUtils.startAdvancedMassageActivity(this);
            }

        }
    }

    public void checkAutoStop() {
        Observable.interval(0, 100, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        String auto = DataManager.getInst().getAuto();
                        if (mCount < 10) {
                            if (auto.equals("0")) {
                                ActivityUtils.startAdvancedMassageActivity(HomeActivity7506.this);
                                mCount = 0;
                                cancleloading();
                                mDisposable.dispose();
                            }
                            mCount++;
                        } else {
                            cancleloading();
                            mCount = 0;
                            mDisposable.dispose();
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mCount = 0;
                        mDisposable.dispose();
                        cancleloading();
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
        }
        return false;
    }


    private void stopAuto() {
        CommondManager.getInst().sendShortCommond(CommmandNum.FINISH, new NormalCallback() {
            @Override
            public void onSuccess(BaseResponse<String> program) {

                Log.e("HomeActivity7506", "onsucceed");
                showloading();
                checkAutoStop();
            }

            @Override
            public void onFailure(String error) {
                ToastUtils.showShortToast(HomeActivity7506.this, "关闭自动程序失败,请检查网络");
            }
        });
    }

    /**
     * 双击退出
     */
    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;
            // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000);
        } else {

            finish();
            System.exit(0);
        }
    }


    @Override
    public void getOnlineSucceed() {
        Log.e("HomeActivity_tag", "getOnlineSucceed");
        repeatCount=0;
        mPresenter.getDataAfterLine(false,false);
    }

    @Override
    public void getOnlineFail() {
        canclekProgress();
        if (CommonUtil.isActivityTop(HomeActivity7506.class, this)) {
            ToastUtils.showShortToast(this, "未检测到设备在线，请检查设备是否通电，或配网后使用");
        }


    }

    @Override
    public void onPermissionSuccess() {
        super.onPermissionSuccess();
        ActivityUtils.startSoftApActivity(this);

    }

    @Override
    public void initSucceed() {

        mPresenter.getToken();
        Log.e("HomeActivity_tag", "initSucceed");

        titleBar.initData();
        setRunning();
    }

    private void setRunning() {
        if (DataManager.getInst().getAuto().equals("0") && DataManager.getInst().isAdvanceRunning()) {
            mRlRunning.setVisibility(View.VISIBLE);
            mRunning=2;
            mTvRunning.setText("正在执行高级按摩");
        }


    }

    @Override
    public void initFail(boolean isrefresh,boolean isSoftAp) {
        Log.e("failed","initfail"+isrefresh);
        int  count  = 3;
        if(isrefresh||isSoftAp){
            count =6;
        }
        if(repeatCount<count){
            repeatCount++;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getRepeatData(isrefresh);
                }
            },500);

        }else {
            canclekProgress();
            if (CommonUtil.isActivityTop(HomeActivity7506.class, this)) {

                ToastUtils.showLongToast(HomeActivity7506.this, "初始化失败...");
            }

        }

    }

    private void getRepeatData(boolean isrefresh){
        Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                        mDisposable =d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        mPresenter.getDataAfterLine(isrefresh,false);
                        mDisposable.dispose();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mDisposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    public void getTokenSucceed(String token) {
        canclekProgress();
        Log.e("HomeActivity_tag", "getTokenSucceed");
        Log.e("SockeStatus_HomeToken2", token + "");
        connectSocket(token);
    }

    @Override
    public void getTokenFail() {
        canclekProgress();
        Log.e("failed","getTokenFail");
        if (CommonUtil.isActivityTop(HomeActivity7506.class, this)) {
            ToastUtils.showLongToast(HomeActivity7506.this, "初始化失败...");
        }
    }


    @Override
    public void toProMasDetailActivity(String name) {
        if (!DataManager.getInst().getValue(CommmandNum.mStatusRunning).equals("0")) {
            if (!CommonUtil.isActivityTop(ProMasDetailActivity7506.class, this) &&
                    !CommonUtil.isActivityTop(ProMasDetailActivity7506L.class, this)&&
                    !CommonUtil.isActivityTop(SoftApOldActivity.class, this) &&
                    !CommonUtil.isActivityTop(SoftApNewActivity.class, this)
                    && !CommonUtil.isActivityTop(ScanShoulderActivity7506.class, this)&&
                    !CommonUtil.isActivityTop(ShouldersAdjustmentActivity7506.class, this)
            ) {
                Log.e("toProMasDetailActivity", "" + name+">>>is7506L=="+is7506L);
                mAutoName = name;
                mRunning=1;
                mRlRunning.setVisibility(View.VISIBLE);
                mTvRunning.setText("正在执行专业按摩：" + name);
                if(is7506L){
                    ActivityUtils.startProMasDetailActivityL(this,name);
                }
                else {
                    ActivityUtils.startProMasDetailActivity(this,name);
                }

            }
        }
    }

    /**
     * 高级按摩
     */
    @Override
    public void toProAdvanceActivity() {
        if (!DataManager.getInst().getValue(CommmandNum.mStatusRunning).equals("0")) {
            if (!CommonUtil.isActivityTop(AdvancedMassageActivity7506.class, this) && !CommonUtil.isActivityTop(SoftApOldActivity.class, this)) {
                Log.e("AdvancedActivity7506", "111");
                mRunning=2;
                mRlRunning.setVisibility(View.VISIBLE);
                mTvRunning.setText("正在执行高级按摩");
                ActivityUtils.startAdvancedMassageActivity(this);
            }
        }
    }

    @Override
    public void closeOther() {
        if (!CommonUtil.isActivityTop(this.getClass(), this)) {
            ActivityUtils.startHomeActivity(this);
        }
    }

    @Override
    public void showRunning(String show, String name) {
        Log.e("showRunning",name+"==="+show);
        if (TextUtils.isEmpty(show)) {
            mRunning = 0;
            mRlRunning.setVisibility(View.GONE);
        } else {
            if (TextUtils.isEmpty(name)) {
                mRunning = 2;
            } else {
                mAutoName = name;
                mRunning = 1;
            }
            mRlRunning.setVisibility(View.VISIBLE);
            mTvRunning.setText(show);
        }
    }

    @Override
    public void updataTime(String min, String sec) {
        doUpDataTime(min,sec);
    }

    @Override
    public void isPause(boolean isPause) {
        if(isPause){
            pauseTime();
        }
        else {
            reStarTime();
        }
    }

    @Override
    public void timeFinish() {
        super.timeFinish();
        if(CommonUtil.isActivityTop(HomeActivity7506.class,this)){
            showFinishDialog(this,"0", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cancleFinishDialog();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataManager.getInst().setConnectSocket(false);
        SoftApSucceedObserver.getInst().removeObserver(this);
        unregisterReceiver(networkChangeReceiver);

        mPresenter.onDestory();
    }

    @Override
    public void connected() {
        Log.e("SockeStatus", "connected==" + WebSocketClient.getInstance(getApplication()).isConnected());
        DataManager.getInst().setConnectSocket(true);
    }

    @Override
    public void connecting() {

    }

    @Override
    public void message(String text, SocketModel object) {
        if (object != null && object.getKey() != null) {
            myHandler.obtainMessage(1, object).sendToTarget();

        }


    }

    @Override
    public void isSoftApOk() {
        mTvNoNet.setVisibility(View.GONE);
        showkProgress("初始化中，请稍等...");
        repeatCount=0;
        mPresenter.getDataAfterLine(false,true);
    }


    private class MyHandler extends Handler {
        WeakReference<HomeActivity7506> mHomeActivity7506WeakReference;

        MyHandler(HomeActivity7506 mHomeActivity7506) {
            mHomeActivity7506WeakReference = new WeakReference<>(mHomeActivity7506);
        }

        @Override
        public void handleMessage(Message msg) {
            final HomeActivity7506 mHomeActivity7506 = mHomeActivity7506WeakReference.get();
            if (mHomeActivity7506 != null) {
                switch (msg.what) {
                    case 1:
                        SocketModel object = (SocketModel) msg.obj;
                        if (object.getKey() != null && object.getValue() != null) {
                            if(object.getKey().equals(CommmandNum.mStatusTIME)){

//                                mTime = object.getValue();
                            }
                            Log.e("getSocket", object.getName() + "===" + object.getKey() + "====" + object.getValue());
                            DataManager.getInst().putKeyValue(object.getKey(), object.getValue());
                            SocketDataObserver.getInst().noticeSocket(object);

                        }

                        break;

                }
            }
        }
    }

    @Override
    public void disconnected(boolean reconnect) {
        if (reconnect) {
            //重连
            DataManager.getInst().setConnectSocket(false);
            mPresenter.getOnline(HomeActivity7506.this, DataManager.getInst().getmSn());

        }
    }

    private void chekcUpData() {
        new Handler().post(new Runnable() {
            public void run() {
                //如果进入应用时没检查 则再检查一次更新
                if (null == DataManager.getInst().getmUpdataBean()) {
                    //检查网络更新
                    CommondManager.getInst().getUpdata(HomeActivity7506.this, new GetUpdataCallback() {
                        @Override
                        public void onGetOnlineSuccess(BaseResponse<BeanUpdata> program) {
                            Log.e("checkUpdata", "checkUpdata_succeed");
                            DataManager.getInst().setHasCheckUpdataOk(true);
                            BeanUpdata bean = program.getData();
                            if (bean.getIsupgrade() == 1) {
                                if(bean.getIsforce()==1){
                                    mSp.setStringValueAndCommit(Constants.SAVE_VERSION, bean.getAppversion());
                                    mSp.setIntValueAndCommit(Constants.SAVE_COUNT, 0);
                                    doUpdata(bean);
                                }
                                else {
                                    if (!mSaveVersion.equals(bean.getAppversion())) {
                                        mSp.setStringValueAndCommit(Constants.SAVE_VERSION, bean.getAppversion());
                                        mSp.setIntValueAndCommit(Constants.SAVE_COUNT, 1);
                                        doUpdata(bean);
                                    } else if (mSaveCount <= 3) {
                                        mSp.setIntValueAndCommit(Constants.SAVE_COUNT, mSaveCount + 1);
                                        doUpdata(bean);
                                    }
                                }


                            }

                        }

                        @Override
                        public void onGetOnlineFailure() {
                            DataManager.getInst().setHasCheckUpdataOk(false);
                            Log.e("checkUpdata", "checkUpdata_onGetOnlineFailure");
                        }
                    });
                }
            }
        });


    }


    class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(CommonUtil.isFastClick()){
                return;
            }
            Log.e("TopActivity",CommonUtil.ActivityTop(HomeActivity7506.this)+"");
            if(!CommonUtil.isActivityTop(SoftApNewActivity.class,HomeActivity7506.this)
                    &&!CommonUtil.isActivityTop(SoftApOldActivity.class,HomeActivity7506.this)
                    &&!CommonUtil.ActivityTop(HomeActivity7506.this).contains("WifiSettingsActivity")){
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isAvailable()) {
                    Log.e("NetWork", "当前网络可用");
                    DataManager.getInst().setNetCanUse(true);
                    chekcUpData();
                    mTvNoNet.setVisibility(View.GONE);
                    if (isFirst) {
                        isFirst = false;
                        return;
                    }
                    if(!hasFristConnect){
                        mPresenter.getOnline(HomeActivity7506.this, DataManager.getInst().getmSn());
                    }
                    Log.e("WebSocketClientc", "=="+WebSocketClient.getInstance(getApplication()).isConnected());
//                    if (!WebSocketClient.getInstance(getApplication()).isConnected()) {
//                        WebSocketClient.getInstance(getApplication()).disconnect();
//                        WebSocketClient.getInstance(getApplication()).onDestroy();
//                        DataManager.getInst().setConnectSocket(false);
//                        mPresenter.getOnline(HomeActivity7506.this, DataManager.getInst().getmSn());
//                    }


                } else {
                    Log.e("NetWork", "当前网络不可用");
                    mRlRunning.setVisibility(View.GONE);
                    mTvNoNet.setVisibility(View.VISIBLE);
                    if (isFirst) {
                        isFirst = false;
                        return;
                    }

                }
            }



        }
    }




}
